package com.test.lucene.index;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.lucene.index.IndexCommitPoint;
import org.apache.lucene.index.IndexDeletionPolicy;
import org.apache.lucene.store.Directory;

/**
 * Delete a commit only when it has been obsoleted by N seconds.
 * 
 * Copy of file
 * {@link http://svn.apache.org/repos/asf/lucene/java/trunk/src/test/org/apache/lucene/index/TestDeletionPolicy.java}
 */
class ExpirationTimeDeletionPolicy implements IndexDeletionPolicy {

    /** Standard logger. */
    private final Log logger = LogFactory
            .getLog(ExpirationTimeDeletionPolicy.class);

    /** Used to convert from milliseconds to seconds. */
    private static final double ONE_THOUSAND = 1000.0;

    /** The Lucene directory. */
    private Directory dir;

    /** Delete any commits which expired. */
    private double expirationTimeSeconds;

    /** How many commits were deleted. */
    private int numDelete;

    /**
     * Constructor.
     * 
     * @param directory
     *            The Lucene directory.
     * @param seconds
     *            Delete any commits which expired.
     */
    public ExpirationTimeDeletionPolicy(final Directory directory,
            final double seconds) {
        this.dir = directory;
        this.expirationTimeSeconds = seconds;
    }

    /** {@inheritDoc} */
    public void onInit(final List commits) throws IOException {
        onCommit(commits);
    }

    /** {@inheritDoc} */
    public void onCommit(final List commits) throws IOException {
        IndexCommitPoint lastCommit = (IndexCommitPoint) commits.get(commits
                .size() - 1);

        // Any commit older than expireTime should be deleted:
        double expireTime = dir.fileModified(lastCommit.getSegmentsFileName())
                / ONE_THOUSAND - expirationTimeSeconds;

        Iterator it = commits.iterator();

        while (it.hasNext()) {
            IndexCommitPoint commit = (IndexCommitPoint) it.next();
            double modTime = dir.fileModified(commit.getSegmentsFileName())
                    / ONE_THOUSAND;
            if (commit != lastCommit && modTime < expireTime) {
                if (logger.isDebugEnabled()) {
                    logger.debug("onCommit() delete ["
                            + commit.getSegmentsFileName() + "]");
                }
                commit.delete();
                numDelete += 1;
            }
        }
    }
}
